package main

import (
	"bufio"
	"fmt"
	"lsmtree"
	"lsmtree/config"
	"os"
	"time"
)

type TestValue struct {
	A int64
	B int64
	C int64
	D string
}

func main() {
	testResetWalBug()
}

func testResetWalBug() {
	defer func() {
		r := recover()
		if r != nil {
			fmt.Println(r)
			inputReader := bufio.NewReader(os.Stdin)
			_, _ = inputReader.ReadString('\n')
		}
	}()

	lsmtree.Start(config.Config{
		DataDir:          "./data",
		Level0Size:       100,
		PartSize:         4,
		Threshold:        9,
		CheckInterval:    2,
		CompressInterval: 2,
	})

	insertValuesByCount(10, 10)
	time.Sleep(2 * time.Second)
	insertValuesByCount(6, 0)
	keys := []string{"0", "1", "2", "3", "4", "5"}
	queryByKeys(keys)
	time.Sleep(10 * time.Second)

	insert()
	query()
}

func insertValuesByCount(count, startFrom int) {
	start := time.Now()
	// 64字节
	testV := TestValue{
		A: 1,
		B: 1,
		C: 3,
		D: "00000000000000000000",
	}

	for i := 0; i < count; i++ {
		lsmtree.Set(fmt.Sprint(i+startFrom), testV)
	}

	elapse := time.Since(start)
	fmt.Println("Insert Complete, dataCount: ", count, " cost time: ", elapse)
}

func insert() {
	testV := TestValue{
		A: 1,
		B: 1,
		C: 3,
		D: "00000000000000000000",
	}

	count := 0
	start := time.Now()

	key := []byte{'a', 'a', 'a', 'a', 'a', 'a'}
	lsmtree.Set(string(key), testV)

	for a := 0; a < 26; a++ {
		for b := 0; b < 26; b++ {
			for c := 0; c < 26; c++ {
				for d := 0; d < 26; d++ {
					for e := 0; e < 26; e++ {
						for f := 0; f < 26; f++ {
							key[0] = 'a' + byte(a)
							key[1] = 'a' + byte(b)
							key[2] = 'a' + byte(c)
							key[3] = 'a' + byte(d)
							key[4] = 'a' + byte(e)
							key[5] = 'a' + byte(f)
							lsmtree.Set(string(key), testV)
							count++
						}
					}
				}
			}
		}
	}
	elapse := time.Since(start)
	fmt.Println("插入完成，数据量：", count, ",消耗时间：", elapse)
}

func queryByKeys(keys []string) {
	for _, key := range keys {
		start := time.Now()
		v, _ := lsmtree.Get[TestValue](key)
		elapse := time.Since(start)
		fmt.Printf("查询 %s 键值，结果：%v, 耗时：%v\n", key, v, elapse)
		fmt.Println(v)
	}
}

func query() {
	start := time.Now()
	v, _ := lsmtree.Get[TestValue]("aaaaaa")
	elapse := time.Since(start)
	fmt.Println("查找 aaaaaa完成，消耗时间：", elapse)
	fmt.Println(v)

	start = time.Now()
	v, _ = lsmtree.Get[TestValue]("aazzzz")
	elapse = time.Since(start)
	fmt.Println("查找 aazzzz完成，消耗时间：", elapse)
	fmt.Println(v)
}
